package org.itboys.shop.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.cookie.CookieUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.seller.constant.SellerCookieConstant;
import org.itboys.seller.entity.SellerUser;
import org.itboys.seller.service.SellerUserService;
import org.itboys.seller.utils.SellerCookieHolder;
import org.itboys.seller.utils.SellerSessionHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 店铺平台登录页
 * @author weisky
 *
 * 2016年5月3日
 */
@RestController
@RequestMapping("/shop")
public class ShopLoginController extends BaseController{
	
	@Autowired
	private SellerUserService sellerUserService;

	/**
	 * 进入登入页面
	 * @param id
	 * @param response
	 */
	@RequestMapping("/login")
	public ModelAndView login(Model model,HttpServletRequest request){
		//登入过的用户名一般放在cookieli里
		model.addAttribute("username", SellerCookieHolder.getSellerUserName());
		//model.addAttribute("isPassword", AdminCookieHolder.getAdminPassword());
		return new ModelAndView("login");
	}
	
	/**
	 * 异步登入地址
	 * @param user
	 * @param response
	 */
	@RequestMapping("/doLogin")
	public void doLogin(SellerUser sellerUser,
			@RequestParam String yzm,
			HttpServletRequest request,HttpServletResponse response){
		
		String _yzm = (String) request.getSession().getAttribute("shopRand");
		if(!StringUtils.equals(_yzm, yzm)){
			AjaxUtils.renderText(response, "-3");//验证码不正确
			return ;
		}
		
		if(StringUtils.isBlank(sellerUser.getUserName())){
			AjaxUtils.renderText(response, "-1");//用户名不能为空
			return ;
		}
		
		if(StringUtils.isBlank(sellerUser.getPassword())){
			AjaxUtils.renderText(response, "-2");//密码不能为空
			return ;
		}
		
		int su = sellerUserService.login(sellerUser.getUserName(), sellerUser.getPassword(), response);
		
		if(su == 1){
			AjaxUtils.renderText(response, "1");//登入成功
		}else if(su == -3){
			AjaxUtils.renderText(response, "-4");//账号被冻结
		}else{
			AjaxUtils.renderText(response, "0");//登陆失败
		}
		
	}
	
	/**
	 * 异步退出
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/logout")
	public ModelAndView logout(HttpServletRequest request,HttpServletResponse response,Model model){
		request.getSession().setAttribute(SellerCookieConstant.COOKIE_USER_NAME, null);
		CookieUtils.removeCookie(response, SellerCookieConstant.COOKIE_PASSWORD);
		SellerSessionHolder.removeSellerUserId();
		return new ModelAndView("redirect:/shop/login"); 
	}
}
